import os
import pwd
import sys
#******************************************************************************
# File: 
#		python.py
# Recipe: 1.2
#		Establishing a Default Value
# Version:
#		0.1
# Author:
#   	Yubei Zhu
# Mail:
#		yubeizhu@gmail.com
# Created at:
#   	2012-08-16  
# Last Update:
#   	2012-08-16
# License: 
#		GPLv3	
#******************************************************************************


################################### Using Scalar ###################################

firstlist = [ None, 0, "0", 0.0, "0.0", 00000, "00000", "", " ", 23, 32, [ ] ]
second = "backup" 

# Pay attention to the values which are false
for index in range(len(firstlist)):
	# use first if first is true, else second
	value = firstlist[ index ] or second
	if firstlist[ index ]:
		print "print [ %d ] I'm first: [%s]" %( index, value )		
	else:
		print "print [ %d ] I'm second: [%s], first is [%s]" %( index, value, firstlist[ index ] )	

# Self reset method, can use the perl's way
flag, reset = 0, 1
flag = flag or reset
print "flag:",flag

# Only Regard None as false
# Use 'is not None' and python's three-way test
notdefined = None

# use first if first is not a none value, else second
# property and / or operator
value = notdefined if notdefined is not None else second # From python 2.5
value = notdefined is not None and notdefined or second  # Before python 2.5, not so readable
print "Value is:", value

# Test element from a list
# Test the length of list before indexing it.
# Or we can use try-exception method
dirname = sys.argv[ 1 ] if len( sys.argv ) > 1 else "/tmp"
print "Dirname:", dirname


# Mutiple candidate values
# os.getlogin
#	The current login from /etc/utmp
# pwd.getpwuid --> get entry record( list ) from passwd file:
#	name,passwd,uid,gid,quota,comment,gcos,dir,shell
#	pwd: passwordd database
# uid os.getuid()
user = os.environ["USER"] or os.environ["LOGNAME"] or\
       os.getlogin( ) or pwd.getpwuid( os.getuid() )[ 0 ] or\
	   "Unknown uid number %" % os.getuid(); 
print "User:",user

################################### Using List ###################################
# use or to assign a default list
# null list will be regard as false
nums   = range( 1, 11 )
seconds = range( 101, 111 )

defaultlist = nums or seconds 
print "Default list first list:",defaultlist

# null list is regarded as false
defaultlist = [ ] or seconds
print "Default list second list:",defaultlist






